﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.CMS.Common.Entity;
using Runda.CMS.Bll;
using Runda.CMS.Common.Utility;
using System.Data;

namespace Runda.CMS.Portal.SysManage
{
    public partial class UserAdd : BasePage
    {
        public Guid UserID
        {
            get
            {
                if (ViewState["UserID"] == null) return Guid.Empty;
                else return new Guid(ViewState["UserID"].ToString());
            }
            set { ViewState["UserID"] = value; }
        }

        public string DepartmentName
        {
            get
            {
                if (ViewState["DepartmentName"] == null) return "";
                else return ViewState["DepartmentName"].ToString();
            }
            set { ViewState["DepartmentName"] = value; }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                treeDepartmentDataRight.Attributes.Add("OnClick", "OnTreeNodeChecked()");
                treeProductCategory.Attributes.Add("OnClick", "OnTreeNodeChecked()");
                InitForm();

                if (Request.QueryString["UserID"] != null)
                {
                    UserID = new Guid(Request.QueryString["UserID"]);
                    SetFormData();
                }

                BindTree();
                if (DepartmentName != "")
                {
                    lblDept.Text = DepartmentName.Substring(1);
                }
            }
        }

        private void InitForm()
        {   
            List<SqlDbParameter> parms = new List<SqlDbParameter>();
            SqlDbParameter parm = new SqlDbParameter();
            parm.ColumnName = "Deleted";
            parm.ColumnType = DbType.Byte;
            parm.ParameterName = "@Deleted";
            parm.ParameterValue = 0;
            parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
            parms.Add(parm);

            SysRoleBll bll = new SysRoleBll();
            cblRoles.DataSource = bll.GetAll<SysRoleEntity>(parms);
            cblRoles.DataTextField = "RoleName";
            cblRoles.DataValueField = "RoleID";
            cblRoles.DataBind();
        }
        private void SetFormData()
        {
            if (UserID != Guid.Empty)
            {
                SysUserEntity entity = null;//
                SysUserBll bll = new SysUserBll();
                entity = bll.Get<SysUserEntity>(UserID);

                List<SqlDbParameter> parms = new List<SqlDbParameter>();
                SqlDbParameter parm = new SqlDbParameter();
                parm.ColumnName = "UserID";
                parm.ColumnType = DbType.Guid;
                parm.ParameterName = "@UserID";
                parm.ParameterValue = entity.UserID;
                parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
                parms.Add(parm);
                entity.UserRoleRelationList = new SysUserRoleRelationBll().GetAll<SysUserRoleRelationEntity>(parms);

                txtAccount.Text = entity.Account;
                txtUserName.Text = entity.UserName;
                txtEmail.Text = entity.Email;
                ddlIsSaleor.SelectedValue = entity.IsSaleor.ToString();
                ddlIsManager.SelectedValue = entity.IsManager.ToString();
                foreach (ListItem item in cblRoles.Items)
                { 
                    Predicate<SysUserRoleRelationEntity> predicate = 
                        delegate(SysUserRoleRelationEntity ent)
                        {
                            if(ent.RoleID == new Guid(item.Value))return true;
                            return false;
                        };
                    bool IsExists = entity.UserRoleRelationList.Exists(predicate);
                    if (IsExists)
                        item.Selected = true;
                }
            }
        }

        
        protected void lnkbtnSave_Click(object sender, EventArgs e)
        {
            string Message = "";
            if (!Save(ref Message))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveandcloseerror", "alert('" + Message + "');", true);
            }
            else
            ClientScript.RegisterStartupScript(this.GetType(), "save", "alert('保存成功');", true);
        }

        protected void lnkbtnSaveAndClose_Click(object sender, EventArgs e)
        {
            string Message = "";
            if (!Save(ref Message))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('" + Message + "');", true);
            }
            else
            ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "window.close();", true);
        }

        protected void lnkbtnSaveAndNew_Click(object sender, EventArgs e)
        {
            string Message = "";
            if (!Save(ref Message))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveansrror", "alert('" + Message + "');", true);
            }
            else
            {
                UserID = Guid.Empty;
                txtAccount.Text = "";
                txtUserName.Text = "";
                ClientScript.RegisterStartupScript(this.GetType(), "saveandnew", "alert('保存成功');", true);
            }
        }

        private bool Save(ref string Message)
        {
            if (treeDepartment.CheckedNodes.Count == 0)
            {
                Message = "请选择部门";
                return false;
            }
            SystemBll systemBll = new SystemBll();
            SysUserEntity entity = null;

            //检查Account是否存在
            SysUserBll bll = new SysUserBll();
            List<SysUserEntity> entityList= new List<SysUserEntity>();
            if (UserID == Guid.Empty)
            {
                List<SqlDbParameter> parms = new List<SqlDbParameter>();
                SqlDbParameter parm = new SqlDbParameter();
                parm.ColumnName = "Account";
                parm.ColumnType = DbType.String;
                parm.ParameterName = "@Account";
                parm.ParameterValue = txtAccount.Text.Trim();
                parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
                parms.Add(parm);

                entityList = bll.GetAll<SysUserEntity>(parms);
                if (entityList.Count > 0)
                {
                    Message = "您输入的帐号已存在";
                    return false;
                }
            }
            else 
            {
                List<SqlDbParameter> parms = new List<SqlDbParameter>();
                SqlDbParameter parm = new SqlDbParameter();
                parm.ColumnName = "Account";
                parm.ColumnType = DbType.String;
                parm.ParameterName = "@Account";
                parm.ParameterValue = txtAccount.Text.Trim();
                parm.QualificationType = SqlDbParameter.QualificationSymbol.NotEqual;
                parms.Add(parm);

                parm = new SqlDbParameter();
                parm.ColumnName = "UserID";
                parm.ColumnType = DbType.Guid;
                parm.ParameterName = "@UserID";
                parm.ParameterValue = UserID;
                parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
                parms.Add(parm);

                entityList = bll.GetAll<SysUserEntity>(parms);
                if (entityList.Count > 0)
                {
                    Message = "您输入的帐号已存在";
                    return false;
                }
            }

            //try save user info
            if (UserID != Guid.Empty)
            {
                entity = bll.Get<SysUserEntity>(UserID);
            }
            else
            {
                entity = new SysUserEntity();
                UserID = entity.UserID;
                entity.Password = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile("123456", "MD5");
                entity.CreatedBy = entity.LastModifyBy = CurrentUserID;
                entity.CreatedOn = entity.LastModifyOn = DateTime.Now;
            }

            entity.UserName = txtUserName.Text;
            entity.Account = txtAccount.Text.Trim();
            entity.LastModifyOn = DateTime.Now;
            entity.LastModifyBy = Guid.Empty;
            entity.Email = txtEmail.Text.Trim();
            entity.IsSaleor = System.Convert.ToInt32(ddlIsSaleor.SelectedValue);
            entity.IsManager = System.Convert.ToInt32(ddlIsManager.SelectedValue);
            //保存权限     
            List<SysUserRoleRelationEntity> UserRoleList = new List<SysUserRoleRelationEntity>();
            SysUserRoleRelationEntity UserRoleEntity = null;
            foreach (ListItem item in cblRoles.Items)
            {
                if (item.Selected)
                {
                    UserRoleEntity = new SysUserRoleRelationEntity();
                    UserRoleEntity.RoleID = new Guid(item.Value);
                    UserRoleEntity.UserID = UserID;
                    UserRoleEntity.Deleted = false;
                    UserRoleList.Add(UserRoleEntity);
                }
            }

            entity.UserRoleRelationList = UserRoleList;

            //保存部门
            List<SysUserDepartmentEntity> UserDeptList = new List<SysUserDepartmentEntity>();
            SysUserDepartmentEntity UserDeptEntity = null;
            foreach (TreeNode item in treeDepartment.CheckedNodes)
            {
                if (item.Checked)
                {
                    UserDeptEntity = new SysUserDepartmentEntity();
                    UserDeptEntity.DepartmentID = new Guid(item.Value);
                    UserDeptEntity.UserID = UserID; 
                    UserDeptList.Add(UserDeptEntity);
                }
            }

            entity.UserDepartmentList = UserDeptList;

            //保存部门--数据权限
            List<SysUserDepartmentDataRightEntity> UserDeptDataRightList = new List<SysUserDepartmentDataRightEntity>();
            SysUserDepartmentDataRightEntity UserDeptDataRightEntity = null;
            foreach (TreeNode item in this.treeDepartmentDataRight.CheckedNodes)
            {
                if (item.Checked)
                {
                    UserDeptDataRightEntity = new SysUserDepartmentDataRightEntity();
                    UserDeptDataRightEntity.DepartmentID = new Guid(item.Value);
                    UserDeptDataRightEntity.UserID = UserID;
                    UserDeptDataRightList.Add(UserDeptDataRightEntity);
                }
            }

            entity.UserDepartmentDataRightList = UserDeptDataRightList;

            //保存部门--产品权限
            List<SysUserProductCategoryEntity> UserProductCategoryList = new List<SysUserProductCategoryEntity>();
            SysUserProductCategoryEntity UserProductCategoryEntity = null;
            foreach (TreeNode item in this.treeProductCategory.CheckedNodes)
            {
                if (item.Checked)
                {
                    UserProductCategoryEntity = new SysUserProductCategoryEntity();
                    UserProductCategoryEntity.categoryGUID = new Guid(item.Value);
                    UserProductCategoryEntity.UserID = UserID;
                    UserProductCategoryList.Add(UserProductCategoryEntity);
                }
            }

            entity.UserProductCategoryList = UserProductCategoryList;

            systemBll.SaveUser(entity);
            return true;
        }

        private void BindTree()
        {
            SystemBll bll = new SystemBll();
            DataTable dt = bll.BuildAllDepartment(UserID);

            DataRow[] rows = dt.Select("ParentID is null");

            foreach (DataRow row in rows)
            {
                TreeNode node = CreateNode(row["DepartmentName"].ToString(), true, row["DepartmentID"].ToString());
                node.Checked = row["IsChecked"].ToString() == "1" ? true : false;
                
                treeDepartment.Nodes.Add(node);

                RecursivelyPopulate(dt, node);
            }

            dt = bll.BuildAllDepartmentByDataRight(UserID);

            DataRow[] rows1 = dt.Select("ParentID is null");

            foreach (DataRow row in rows1)
            {
                TreeNode node = CreateNode(row["DepartmentName"].ToString(), true, row["DepartmentID"].ToString());
                node.Checked = row["IsChecked"].ToString() == "1" ? true : false;
                treeDepartmentDataRight.Nodes.Add(node);

                RecursivelyPopulate1(dt, node);
            }

            dt = bll.BuildAllProductCategory(UserID);

            DataRow[] rows2 = dt.Select("parentGUID is null");

            foreach (DataRow row in rows2)
            {
                TreeNode node = CreateNode(row["categoryName"].ToString(), true, row["categoryGUID"].ToString());
                node.Checked = row["IsChecked"].ToString() == "1" ? true : false;
                treeProductCategory.Nodes.Add(node);

                RecursivelyPopulate2(dt, node);
            }

        }

        private void RecursivelyPopulate(DataTable dt, TreeNode node)
        {
            DataRow[] rows = dt.Select("ParentID = '" + node.Value + "'");
            foreach (DataRow row in rows)
            {
                TreeNode TreeNode = CreateNode(row["DepartmentName"].ToString(), false, row["DepartmentID"].ToString());
                TreeNode.Checked = row["IsChecked"].ToString() == "1" ? true : false;
                if (row["IsChecked"].ToString() == "1")
                {
                    DepartmentName += GetDepartmentName(new Guid(row["DepartmentID"].ToString()))+"；";
                }
                node.ChildNodes.Add(TreeNode);
                RecursivelyPopulate(dt, TreeNode);
            }
        }
        private void RecursivelyPopulate1(DataTable dt, TreeNode node)
        {
            DataRow[] rows = dt.Select("ParentID = '" + node.Value + "'");
            foreach (DataRow row in rows)
            {
                TreeNode TreeNode = CreateNode(row["DepartmentName"].ToString(), false, row["DepartmentID"].ToString());
                TreeNode.Checked = row["IsChecked"].ToString() == "1" ? true : false;
                node.ChildNodes.Add(TreeNode);
                RecursivelyPopulate1(dt, TreeNode);
            }
        }

        private void RecursivelyPopulate2(DataTable dt, TreeNode node)
        {
            DataRow[] rows = dt.Select("parentGUID = '" + node.Value + "'");
            foreach (DataRow row in rows)
            {
                TreeNode TreeNode = CreateNode(row["categoryName"].ToString(), false, row["categoryGUID"].ToString());
                TreeNode.Checked = row["IsChecked"].ToString() == "1" ? true : false;
                node.ChildNodes.Add(TreeNode);
                RecursivelyPopulate2(dt, TreeNode);
            }
        }


        private TreeNode CreateNode(string text, bool expanded, string id)
        {
            TreeNode node;
            node = new TreeNode(text, id);
            node.Expanded = expanded;
            node.SelectAction = TreeNodeSelectAction.None;
            return node;
        }

        private string GetDepartmentName(Guid departmentID)
        {
            string deptName = "";

            List<SysDepartmentEntity> dept = new SystemBll().GetParentDepartment(departmentID);
            foreach (SysDepartmentEntity ent in dept)
            {
                deptName += "-" + ent.DepartmentName;
            }

            return deptName;
        }

    }
}
